40. Solution: Add Delete Functionality

Add Delete Functionality Solution

In this exercise you implemented the code to delete an entire database worth of weather data. Wow!

Notes on Solution Code

Note that in the solution code, you only need to implementing delete for the CODE_WEATHER case because you're deleting the entire database. You also don't have to actually use this delete functionality in the app, so it's up to you to run the tests and make sure everything was completed correctly. With that said, here's the code for delete:

@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
    int numRowsDeleted;
    if (null == selection) selection = "1";
    switch (sUriMatcher.match(uri)) {
        case CODE_WEATHER:
            numRowsDeleted = mOpenHelper.getWritableDatabase().delete(
                    WeatherContract.WeatherEntry.TABLE_NAME,
                    selection,
                    selectionArgs);
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    if (numRowsDeleted != 0) {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return numRowsDeleted;
}

Solution Code

Solution: [S09.03-Solution-ContentProviderDelete][Diff]